import {CloseCircleOutlined} from '@ant-design/icons';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  InputNumber,
  message,
  Popover,
  Radio,
  Row,
  Select,
  Steps
} from 'antd';
import React, {useEffect, useState} from 'react';
import {FooterToolbar} from '@ant-design/pro-layout';
import styles from './style.less';
import TableForm from "@/pages/warehouse/stock-product/components/TableForm";
import {queryWarehouse, queryWarehouseByProduct, queryWarehouseProduct} from "@/services/warehouse";
import {queryProcessFlow} from "@/services/product";
import {queryOrderList} from "@/services/order";


const {Option} = Select;
const {RangePicker} = DatePicker;
const fieldLabels = {
  warehouseCode: {
    label: '仓库编码',
    code: 'warehouseCode',
  },
  warehouseId: {
    label: '仓库编码',
    code: 'warehouseId',
  },
  warehouseNum: {
    label: '仓库库存',
    code: 'warehouseNum',
  },
  warehouseName: {
    label: '仓库名称',
    code: 'warehouseName',
  },
  warehouseProductType: {
    label: '产品类型',
    code: 'warehouseProductType',
  },
  orderCode: {
    label: '订单编号',
    code: 'orderCode',
  },
  productionNo: {
    label: '生产编号',
    code: 'productionNo',
  },
  processId: {
    label: '指定工艺段',
    code: 'processId',
  },
  applyBy: {
    label: '领用人',
    code: 'applyBy',
  },
  num: {
    label: '出库数量',
    code: 'num'
  },
  remark: {
    label: '备注',
    code: 'remark',
  },
};

const StockProductForm = (props, {submitting, dispatch}) => {
  const {visible, onSubmit, materialData, type} = props; // type: 2 出库；3 返修 4：报废
  const {TextArea} = Input;
  const {Step} = Steps;
  const [form] = Form.useForm();
  const [error, setError] = useState([]);
  const [warehouseData, setWarehouseData] = useState([]);
  const [processData, setProcessData] = useState([]);
  const [orderData, setOrderData] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [isProcessModalVisible, setIsProcessModalVisible] = useState(false);

  useEffect(() => {
    if (type === 2){
      queryWarehouseProduct({productCode: materialData.productCode, warehouseProductType: 1,pageNum: 1, pageSize: 99999}).then(res => {
        if (res && res.status === '0') {
          setWarehouseData(res.result.records)
        }
      })
    }else {
      queryWarehouse({pageNum: 1, pageSize: 99999}).then(res => {
        if (res && res.status === '0') {
          setWarehouseData(res.result.records)
        }
      })
    }
  }, [])

  useEffect(() => {
    queryProcessFlow({
      pageNum: 1,
      pageSize: 99999,
      isRepairProcess: 1
    }).then(res => {
      setProcessData(res.result.records)
    })
  }, [])

  const getErrorInfo = (errors) => {
    const errorCount = errors.filter((item) => item.errors.length > 0).length;

    if (!errors || errorCount === 0) {
      return null;
    }

    const scrollToField = (fieldKey) => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);

      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };

    const errorList = errors.map((err) => {
      if (!err || err.errors.length === 0) {
        return null;
      }

      const key = err.name[0];
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <CloseCircleOutlined className={styles.errorIcon}/>
          <div className={styles.errorMessage}>{err.errors[0]}</div>
          <div className={styles.errorField}>{fieldLabels[key].label}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={(trigger) => {
            if (trigger && trigger.parentNode) {
              return trigger.parentNode;
            }

            return trigger;
          }}
        >
          <CloseCircleOutlined/>
        </Popover>
        {errorCount}
      </span>
    );
  };

  const onFinish = (values) => {
    if (values.products !== undefined && values.products.length > 0) {
      let isEmpty = false
      values.products.forEach(m => {
        if (!m) {
          isEmpty = true;
          return;
        }
      })
      if (!isEmpty) {
        if (values.products.length > 1) {
          message.error("只能选择一款产品")
        } else {
          console.log(values)
          if (type === 2) { // 如果是正常出库
            values.products[0].warehouseProductType = 1
            if (values.num > values.warehouseNum) {
              message.error("出库数最大值不能超过该仓库库存数")
              return;
            }
          }
          onSubmit(values)
        }
      } else {
        message.error("请选择产品并选择数量")
      }
    } else {
      message.error("请选择产品并选择数量")
    }
  };

  const onFinishFailed = (errorInfo) => {
    //console.log((errorInfo)
    setError(errorInfo.errorFields);
  };


  const handleProcessOk = () => {
    setIsProcessModalVisible(false);
  }

  const handleProcessCancel = () => {
    setIsProcessModalVisible(false);
  }

  const onWarehouseChange = (v, o) => {
    if (type === 2) {
      form.setFieldsValue({
        warehouseId: v,
        warehouseNum: o.warehouse.num
      })
    }else {
      form.setFieldsValue({
        warehouseId: v,
      })
    }
  }

  useEffect(() => {
    const param = type > 1 ? {
      orderStatuses: '9,10',
      productCode: materialData.productCode
    } : {
      orderStatuses: '9,10',
    }
    queryOrderList(param).then(res => {
      if (res && res.status === '0') {
        setOrderData(res.data)
      }
    })
  }, [])

  const onOrderChange = (v, o) => {
    console.log(o.order)
    // form.setFieldsValue({
    //   products: [o.order],
    // })
    setTableData([o.order])
  }

  return (
    <div className={'product-form'}>
      {
        type === 1 ? <Form
          form={form}
          layout="vertical"
          hideRequiredMark
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <>
            <Card title="基本信息" className={styles.card} bordered={false}>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.warehouseName.label}
                    name={fieldLabels.warehouseName.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.warehouseName.label}`,
                      },
                    ]}
                  >
                    <Select onChange={(v, o) => onWarehouseChange(v, o)}>
                      {warehouseData.map(item => {
                        return <Option value={item.warehouseId} key={item.warehouseCode}>{item.warehouseName}</Option>
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.warehouseId.label}
                    name={fieldLabels.warehouseId.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.warehouseId.label}`,
                      },
                    ]}
                  >
                    <Input disabled={true}/>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.warehouseProductType.label}
                    name={fieldLabels.warehouseProductType.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.warehouseName.label}`,
                      },
                    ]}
                  >
                    <Radio.Group>
                      <Radio value={1}>正常产品</Radio>
                      <Radio value={2}>客户退货产品</Radio>
                    </Radio.Group>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.orderCode.label}
                    name={fieldLabels.orderCode.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.orderCode.label}`,
                      },
                    ]}
                  >
                    <Select
                      showSearch
                      defaultActiveFirstOption={false}
                      showArrow={true}
                      filterOption={false}
                      onChange={(v, o) => onOrderChange(v, o)}
                      notFoundContent={null}
                    >
                      {orderData.map(item => {
                        return <Option value={item.orderCode}
                                       key={item.orderCode} order={item}>{item.orderCode}</Option>
                      })}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.remark.label}
                    name={fieldLabels.remark.code}
                  >
                    <TextArea placeholder={`请输入${fieldLabels.remark.label}`}/>
                  </Form.Item>
                </Col>
              </Row>
            </Card>
            <Card title="选择产品" bordered={false}>
              <Form.Item name="products">
                <TableForm disabled={false} oldData={tableData} onChange={(v) => {
                  //console.log((v)
                }}/>
              </Form.Item>
            </Card>
          </>
          <FooterToolbar>
            {getErrorInfo(error)}
            <Button type="primary" onClick={props.onCancel.bind(this, false)}>
              返回
            </Button>
            <Button type="primary" onClick={() => form?.submit()}>
              提交
            </Button>
          </FooterToolbar>
        </Form> : <Form
          form={form}
          layout="vertical"
          initialValues={{
            products: [materialData],
            warehouseId: materialData.warehouseId,
            warehouseName: materialData.warehouseName,
            orderCode: materialData.orderCode,
          }}
          hideRequiredMark
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <>
            <Card title="基本信息" className={styles.card} bordered={false}>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.warehouseName.label}
                    name={fieldLabels.warehouseName.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.warehouseName.label}`,
                      },
                    ]}
                  >
                    <Select onChange={(v, o) => onWarehouseChange(v, o)}>
                      {warehouseData.map(item => {
                        return <Option value={item.warehouseId} key={item.warehouseCode} warehouse={item}>{item.warehouseName}</Option>
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.warehouseId.label}
                    name={fieldLabels.warehouseId.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.warehouseId.label}`,
                      },
                    ]}
                  >
                    <Input disabled={true}/>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.warehouseNum.label}
                    name={fieldLabels.warehouseNum.code}
                  >
                    <Input disabled={true}/>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16} style={{display: type > 1 ? 'block' : 'none'}}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={type === 3 ? '返修数量' : (type === 4 ? '报废数量' : fieldLabels.num.label)}
                    name={fieldLabels.num.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.num.label}`,
                      },
                      {
                        pattern: /^[1-9]\d*$/,
                        message: '只能输入整数'
                      }
                    ]}
                  >
                    <InputNumber max={materialData.num} min={1}
                                 placeholder={`请输入${type === 3 ? '返修数量' : (type === 4 ? '报废数量' : fieldLabels.num.label)}`}
                                 style={{width: '100%'}}/>
                  </Form.Item>
                </Col>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.orderCode.label}
                    name={fieldLabels.orderCode.code}
                    rules={[
                      {
                        required: true,
                        message: `请输入${fieldLabels.orderCode.label}`,
                      },
                    ]}
                  >
                    <Select
                      disabled={type === 2} // 正常出货，orderCode不用选择
                      showSearch
                      defaultActiveFirstOption={false}
                      showArrow={true}
                      filterOption={false}
                      notFoundContent={null}
                    >
                      {orderData.map(item => {
                        return <Option value={item.orderCode}
                                       key={item.orderCode}>{item.orderCode}</Option>
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                {/* 返修指定工艺 */}
                <Col lg={8} md={12} sm={24} style={{display: type === 3 ? '' : 'none'}}>
                  <Form.Item
                    label={fieldLabels.processId.label}
                    name={fieldLabels.processId.code}
                    // rules={[
                    //   {
                    //     required: true,
                    //     message: `请输入${fieldLabels.processId.label}`,
                    //   },
                    // ]}
                  >
                    <Select>
                      {
                        processData.map(item => {
                          return <Option value={item.processId} key={item.processId}>{item.processName}</Option>
                        })
                      }
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={16}>
                <Col lg={8} md={12} sm={24}>
                  <Form.Item
                    label={fieldLabels.remark.label}
                    name={fieldLabels.remark.code}
                  >
                    <TextArea placeholder={`请输入${fieldLabels.remark.label}`}/>
                  </Form.Item>
                </Col>
              </Row>
            </Card>
            <Card title="选择产品" bordered={false}>
              <Form.Item name="products">
                <TableForm disabled={true} onChange={(v) => {
                  //console.log((v)
                }}/>
              </Form.Item>
            </Card>
          </>
          <FooterToolbar>
            {getErrorInfo(error)}
            <Button type="primary" onClick={props.onCancel.bind(this, false)}>
              返回
            </Button>
            <Button type="primary" onClick={() => form?.submit()}>
              提交
            </Button>
          </FooterToolbar>
        </Form>
      }


    </div>
  );
};

// export default connect(({ loading }) => ({
//   submitting: loading.effects['productForm/submitAdvancedForm'],
// }))(ProductForm);
export default StockProductForm;
